package com.xy.webadmin.app.schedule;

import com.xy.webadmin.app.constant.MqttConstants;
import com.xy.webadmin.app.model.MqttBrokerConfig;
import com.xy.webadmin.app.service.MqttApiService;
import com.xy.webadmin.app.service.MqttBrokerConfigService;
import com.xy.webadmin.app.vo.MqttDeviceStatusVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * MQTT缓存刷新定时任务
 *
 * @author xiaoyue
 * @date 2025-07-10
 */
@Slf4j
@Component
public class MqttCacheRefreshSchedule {

    @Autowired
    private MqttBrokerConfigService mqttBrokerConfigService;
    
    @Autowired
    private MqttApiService mqttApiService;
    
    @Autowired
    @Qualifier("mqttCacheManager")
    private CacheManager mqttCacheManager;
    
    /**
     * 每5分钟刷新一次设备状态缓存
     */
    @Scheduled(fixedRate = MqttConstants.Schedule.CACHE_REFRESH_INTERVAL)
    public void refreshDeviceStatusCache() {
        log.info("开始刷新MQTT设备状态缓存");
        
        // 手动清除缓存
        Cache deviceStatusCache = mqttCacheManager.getCache(MqttConstants.Cache.DEVICE_STATUS);
        Cache deviceStatusByCompanyCache = mqttCacheManager.getCache(MqttConstants.Cache.DEVICE_STATUS_BY_COMPANY);
        
        if (deviceStatusCache != null) {
            deviceStatusCache.clear();
            log.info("已清除设备状态缓存");
        }
        
        if (deviceStatusByCompanyCache != null) {
            deviceStatusByCompanyCache.clear();
            log.info("已清除公司设备状态缓存");
        }
        
        try {
            // 获取所有MQTT配置
            List<MqttBrokerConfig> configs = mqttBrokerConfigService.getMqttBrokerConfigList(null, null);
            log.info("找到{}个MQTT配置需要刷新缓存", configs.size());
            
            int successCount = 0;
            int failCount = 0;
            
            for (MqttBrokerConfig config : configs) {
                if (config == null || config.getId() == null) {
                    log.warn("跳过无效的MQTT配置");
                    continue;
                }
                
                try {
                    log.debug("开始刷新配置ID: {}的设备状态", config.getId());
                    // 使用带缓存的方法，这样结果会自动放入缓存
                    // 因为我们已经清除了缓存，所以这里会执行实际的方法体
                    MqttDeviceStatusVo deviceStatusSummary = mqttApiService.getDeviceStatusSummary(config.getId());
                    log.info("deviceStatusSummary:{}",deviceStatusSummary
                    );
                    log.debug("已刷新配置ID: {}的设备状态", config.getId());
                    successCount++;
                } catch (Exception e) {
                    failCount++;
                    log.error("刷新设备状态失败，configId: {}, error: {}", config.getId(), e.getMessage());
                    // 不抛出异常，继续处理下一个配置
                }
            }
            
            // 刷新公司级缓存
            try {
                // 这里可以添加公司级缓存刷新逻辑，如果需要的话
            } catch (Exception e) {
                log.error("刷新公司级设备状态缓存失败: {}", e.getMessage());
            }
            
            log.info("MQTT设备状态缓存刷新完成，成功: {}, 失败: {}, 总计: {}", 
                    successCount, failCount, configs.size());
        } catch (Exception e) {
            log.error("MQTT设备状态缓存刷新过程中发生错误: {}", e.getMessage(), e);
        }
    }
} 